package com.wind.sqlite.controller;


import com.wind.sqlite.bean.PasswordBean;
import com.wind.sqlite.common.utils.R;
import com.wind.sqlite.common.validator.Assert;
import com.wind.sqlite.entity.SysUserEntity;
import com.wind.sqlite.service.SysUserService;
import com.wind.sqlite.common.utils.R;
import com.wind.sqlite.entity.SysUserEntity;
import com.wind.sqlite.service.SysUserService;
import com.wind.sqlite.service.SysUserTokenService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("sys")
public class LoginController  extends AbstractController{

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserTokenService sysUserTokenService;

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {

    }


    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody SysUserEntity form) throws IOException {

        SysUserEntity sysUserEntityQuery =new SysUserEntity();
        sysUserEntityQuery.setUsername(form.getUsername());
        //用户信息
        SysUserEntity user = sysUserService.queryOne(sysUserEntityQuery);

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }


        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(user.getId());
        return r;
    }


    /**
     * 退出
     */
    @PostMapping("logout")
    public R logout() {
        sysUserTokenService.logout(getUserId());
        return R.ok();
    }


}
